package com.sugon.controller.module;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.dao.ModuleReplacePartDao;
import com.sugon.dao.ModuleSpStockDao;
import com.sugon.entity.ModulPositionCorrelationEntity;
import com.sugon.entity.ModuleSpDemandItemEntity;
import com.sugon.entity.ModuleSpPurchasingBatchEntity;
import com.sugon.entity.ModuleSpStockEntity;
import com.sugon.entity.vo.MoldSpQueryParam;
import com.sugon.modules.mold.consts.MoldSpStockState;
import com.sugon.service.ModuleSpDemandItemService;
import com.sugon.service.ModuleSpPurchasingBatchService;
import com.sugon.service.ModuleSpStockService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import com.sugon.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模具备件库存状况Controller
 *
 * @author sugon
 * @date 2021-10-13 16:59:06
 */
@Controller
@RequestMapping("modulespstock")
public class ModuleSpStockController {
    @Autowired
    private ModuleSpStockService moduleSpStockService;
    @Autowired
    private ModuleSpPurchasingBatchService moduleSpPurchasingBatchService;
    @Autowired
    private ModuleReplacePartDao moduleReplacePartDao;
    @Autowired
    private ModuleSpStockDao moduleSpStockDao;
    @Resource
    private ModuleSpDemandItemService moldSpDemandItemService;

    /**
     * 型芯条码扫码入库
     * 生成待入库状态
     *
     * @param uniqueCode 模具型芯唯一码
     */
    @RequiresPermissions("modulespstock:scanStockIn")
    @RequestMapping("/scanStockIn")
    @ResponseBody
    public R scanStockIn(@RequestParam String uniqueCode) {
        // 校验是否已入库
        ModuleSpStockEntity moduleSpStockInDB = moduleSpStockService.queryListByUniqueCode(uniqueCode);
        if (moduleSpStockInDB != null) {
            Integer state = moduleSpStockInDB.getState();
            if (MoldSpStockState.ING.equals(state)) {
                return R.error("已扫码入库中，请勿重复扫码！");
            } else {
                return R.error("已入库，请确认！");
            }
        } else {
            // 识别待入库的型芯属于哪个采购批次的
            ModuleSpPurchasingBatchEntity moduleSpPurchasingBatch = moduleSpPurchasingBatchService.queryBySpUniqueCode(uniqueCode);
            if (moduleSpPurchasingBatch == null) {
                return R.error("无法识别当前型芯条码对应的采购批次信息！");
            }
            ModuleSpStockEntity moduleSpStock = new ModuleSpStockEntity(uniqueCode, moduleSpPurchasingBatch.getId());
            // 识别待入库的型芯属于哪个型芯计划的
            ModuleSpDemandItemEntity demandItem = moldSpDemandItemService.query(moduleSpPurchasingBatch.getId(), uniqueCode);
            if (demandItem != null) {
                moduleSpStock.setDemandItemId(demandItem.getId());
            }
            moduleSpStock.setState(MoldSpStockState.ING);
            return moduleSpStockService.save(moduleSpStock) > 0 ? R.ok() : R.error("扫码入库失败，请稍后重试！");
        }
    }

    /**
     * 型芯条码扫码出库
     *
     * @param uniqueCode 模具型芯唯一码
     */
    @RequiresPermissions("modulespstock:scanStockOut")
    @RequestMapping("/scanStockOut")
    @ResponseBody
    public R scanStockOut(@RequestParam String uniqueCode) {
        // 校验是否已入库
        ModuleSpStockEntity moduleSpStockInDB = moduleSpStockService.queryListByUniqueCode(uniqueCode);
        if (moduleSpStockInDB == null) {
            return R.error("无法匹配，请确认是否已入库！");
        }
        // 校验出库状态
        Integer moldSpStockState = moduleSpStockInDB.getState();
        if (MoldSpStockState.ING.equals(moldSpStockState)) {
            return R.error("当前型芯尚未入库完毕，请确认！");
        } else if (MoldSpStockState.USED.equals(moldSpStockState)) {
            return R.error("当前型芯已使用，请勿重复扫码！");
        } else if (MoldSpStockState.LOCKING.equals(moldSpStockState)) {
            return R.error("当前型芯已扫码出库中，请勿重复扫码！");
        }
        moduleSpStockInDB.setState(MoldSpStockState.LOCKING);
        return moduleSpStockService.update(moduleSpStockInDB) > 0 ? R.ok() : R.error("扫码出库失败，请稍后重试！");
    }

    /**
     * 车间人员入库自己车间的待入库型芯
     * 确认入库
     */
    @RequestMapping("/confirmStockIn")
    @ResponseBody
    public R confirmStockIn() {
        // 获取登录用户所在车间
        String currentWorkshop = ShiroUtils.getWorkshop();
        if (StrUtil.isEmpty(currentWorkshop)) {
            return R.error("登录用户不属于任何车间，不能执行该操作");
        }
        return moduleSpStockService.confirmStockIn(currentWorkshop) ? R.ok() : R.error();
    }

    /**
     * 确认出库备件
     */
    @RequestMapping("/confirmStockOut")
    @ResponseBody
    public R confirmStockOut(@RequestBody String[] ids) {
        // 获取登录用户所在车间
        String currentWorkshop = ShiroUtils.getWorkshop();
        if (StrUtil.isEmpty(currentWorkshop)) {
            return R.error("登录用户不属于任何车间，不能执行该操作");
        }
        return moduleSpStockService.confirmStockOut(ids) ? R.ok() : R.error();
    }

    /**
     * 重置模具型芯状态为扫码前状态
     */
    @RequestMapping("/resetMoldSpStockState")
    @ResponseBody
    public R resetMoldSpStockState(@RequestBody String[] ids) {
        return moduleSpStockDao.resetState(ids, MoldSpStockState.ED) > 0 ? R.ok() : R.error("删除失败，请稍后重试！");
    }

    /**
     * 查看列表
     */
    //@DataFilter(deptAlias = "MSS.WORKSHOP", userAlias = "MSS.CREATE_USER")
    @RequestMapping("/list")
    //@RequiresPermissions("modulespstock:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<ModuleSpStockEntity> moduleSpStockList = moduleSpStockService.queryList(query);
        int total = moduleSpStockService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(moduleSpStockList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("modulespstock:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        ModuleSpStockEntity moduleSpStock = moduleSpStockService.queryObject(id);

        return R.ok().put("moduleSpStock", moduleSpStock);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info")
    //@RequiresPermissions("modulespstock:info")
    @ResponseBody
    public R infoByUniqueCode(@RequestParam("uniqueCode") String uniqueCode) {
        ModuleSpStockEntity moduleSpStock = moduleSpStockService.queryListByUniqueCode(uniqueCode);
        return R.ok().put("moduleSpStock", moduleSpStock);
    }

    @RequestMapping("/loadByUniqueCode")
    @ResponseBody
    @NonBusinessParamValid
    public R loadByUniqueCode(@Validated MoldSpQueryParam queryParam, BindingResult bindingResult) {
        ModuleSpStockEntity moduleSpStock = moduleSpStockService.queryListByUniqueCode(queryParam.getUniqueCode());
        if (moduleSpStock != null && StrUtil.isNotEmpty(moduleSpStock.getUniqueBarCode())) {
            // 获取本次模具换件记录中支持的位置信息
            List<ModulPositionCorrelationEntity> moldPositionList = moduleReplacePartDao.queryModulePosition(queryParam.getMethodType(), queryParam.getReplaceCode());
            if (CollectionUtil.isNotEmpty(moldPositionList)) {
                // 只返回已设置适用条码代码且匹配的位置信息
                moduleSpStock.setPositionList(moldPositionList.stream().filter(moldPosition -> StrUtil.isNotEmpty(moldPosition.getBarCodeRange()) && ReUtil.isMatch(moldPosition.getBarCodeRange(), moduleSpStock.getUniqueBarCode())).collect(Collectors.toList()));
            }
        }
        return R.ok().put("moduleSpStock", moduleSpStock);
    }

    /**
     * 保存
     */
    @AutoLog("模具备件库存状况--保存")
    @RequestMapping("/save")
    //@RequiresPermissions("modulespstock:save")
    @ResponseBody
    public R save(@RequestBody ModuleSpStockEntity moduleSpStock) {
        moduleSpStockService.save(moduleSpStock);

        return R.ok();
    }

    /**
     * 修改
     */
    @AutoLog("模具备件库存状况--修改")
    @RequestMapping("/update")
    //@RequiresPermissions("modulespstock:update")
    @ResponseBody
    public R update(@RequestBody ModuleSpStockEntity moduleSpStock) {
        moduleSpStockService.update(moduleSpStock);

        return R.ok();
    }

    /**
     * 删除
     */
    @AutoLog("模具备件库存状况--删除")
    @RequestMapping("/delete")
    //@RequiresPermissions("modulespstock:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        moduleSpStockService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<ModuleSpStockEntity> list = moduleSpStockService.queryList(params);

        return R.ok().put("list", list);
    }
}
